package com.thor.palmmall.rest.order;

import org.springframework.beans.factory.annotation.Autowired;

import com.thor.commons.entity.BeanOperateInfo;
import com.thor.commons.exception.ThorServiceException;
import com.thor.commons.query.QueryResult;
import com.thor.commons.util.Assert;
import com.thor.commons.util.StringUtil;
import com.thor.palmmall.rest.event.MemberRegisterEvent;
import com.thor.palmmall.rest.order.converter.AOrderConverter;
import com.thor.palmmall.rest.order.converter.SOrderConditionConverter;
import com.thor.palmmall.rest.order.converter.SOrderConverter;
import com.thor.palmmall.spi.common.SQueryResult;
import com.thor.palmmall.spi.common.SQueryResultConverter;
import com.thor.palmmall.spi.common.SResponse;
import com.thor.palmmall.spi.order.SOrder;
import com.thor.palmmall.spi.order.SOrderOperateInfoConverter;
import com.thor.palmmall.spi.order.SOrderService;
import com.thor.palmmall.util.event.GlobalEventBus;

public class AOrderServiceImpl implements AOrderService {

  @Override
  public String saveOrder(AOrder order, BeanOperateInfo operateInfo) throws ThorServiceException {
    Assert.assertArgumentNotNull(operateInfo, "operateInfo");
    if (!StringUtil.isNullOrBlank(order.getMemberCardNo())) {
      MemberRegisterEvent event = new MemberRegisterEvent();
      event.setOrder(order);
      event.setOperateInfo(operateInfo);
      GlobalEventBus.post(event);
    }

    SResponse<String> resp = sOrderService.save(SOrderConverter.getInstance().convert(order),
        SOrderOperateInfoConverter.getInstance().convert(operateInfo));
    if (resp.isSuccess()) {
      return resp.getBody();
    } else {
      throw new ThorServiceException("无法创建订单：" + resp.getMessage());
    }
  }

  @Override
  public AOrder get(String id) throws ThorServiceException {
    SResponse<SOrder> resp = sOrderService.get(id);
    if (resp.isSuccess()) {
      return AOrderConverter.getInstance().convert(resp.getBody());
    } else {
      throw new ThorServiceException("无法找到指定ID的订单：" + resp.getMessage());
    }
  }

  @Override
  public String abort(String id, long version, BeanOperateInfo operateInfo)
      throws ThorServiceException {
    SResponse<String> resp = sOrderService.abort(id, version,
        SOrderOperateInfoConverter.getInstance().convert(operateInfo));
    if (resp.isSuccess()) {
      return resp.getBody();
    } else {
      throw new ThorServiceException("无法作废订单：" + resp.getMessage());
    }
  }

  @Override
  public QueryResult<AOrder> query(AOrderCondition condition) throws ThorServiceException {
    SResponse<SQueryResult<SOrder>> resp = sOrderService
        .query(SOrderConditionConverter.getInstance().convert(condition));
    if (resp.isSuccess()) {
      return SQueryResultConverter.convert(resp.getBody(), AOrderConverter.getInstance());
    } else {
      throw new ThorServiceException("无法查询到订单：" + resp.getMessage());
    }
  }

  @Autowired
  private SOrderService sOrderService;

}
